<template>
    <div class="brief-list">
        <Card style="padding:16px;">
            <Row class="search-form">
                <Col span="20">
                <Form :model="searchItem" inline :label-width="100">
                    <FormItem label="通报标题：">
                        <Input v-model.trim="searchItem.title"
                               clearable
                               placeholder="请输入"
                               :maxlength="20"
                               class="formItemStyle"
                        />
                    </FormItem>
                    <FormItem label="通报类型:" >
                        <Select  v-model="searchItem.type" class="itemsStyle" filterable  placeholder="请选择通报类型"  >
                            <Option v-for="item in typeList" :key="item.id"  :value="item.id+''" >{{item.name}}</Option>
                        </Select>
                    </FormItem>
                </Form>
                </Col>
                <Col span="4" style="text-align: right">
                <Button @click="searchInfo" class="tablePageBtnStyle" type="primary">查询</Button>
                </Col>
            </Row>


            <Row class="search-result">
                <Col span="0">

                </Col>
                <Col span="24" style="text-align: right">
                <Button @click="addNotice" class="tablePageBtnStyle" type="primary">+新建通报</Button>
                </Col>
            </Row>

            <VTable :init='columns'
                    :defaultValue="defaultVal"
                    :pages='true'
                    :filt='filt'
                    @changed="tableCall"
                    :loading="loading"></VTable>


            <!-- 添加通报 -->
            <Modal v-model="addShareModal"
                   width="800"
                   title="添加通报"
                   :mask-closable="false">
                <div>
                    <Form ref="addBriefFormRef" :model="addBriefForm" inline
                          :rules="ruleValidate" :label-width="100" class="addShareModal-form">
                        <FormItem label="通报类型:" prop="type">
                            <Select  v-model="addBriefForm.type" class="itemsStyle" filterable  placeholder="请选择通报类型"  >
                                <Option v-for="item in typeList" :key="item.id"  :value="item.id+''" >{{item.name}}</Option>
                            </Select>
                        </FormItem>
                        <FormItem label="通报标题:" prop="title">
                            <Input v-model.trim="addBriefForm.title" class="itemsStyle" placeholder="最多可输入25字" :maxlength="25"></Input>
                        </FormItem>
                        <FormItem label="通报简介:" prop="resume">
                            <Input v-model.trim="addBriefForm.resume" class="itemsStyle" placeholder="最多可输入25字" :maxlength="25"></Input>
                        </FormItem>
                        <!--<FormItem label="通报人名:" prop="shareName">-->
                            <!--<Input v-model.trim="addBriefForm.shareName" class="itemsStyle" placeholder="最多可输入25字" :maxlength="25"></Input>-->
                        <!--</FormItem>-->
                    </Form>
                    <div>
                        <textarea class='tinymce-textarea' id="tinymceEditerBrief"></textarea>
                        <Spin fix v-if="spinShow">
                            <Icon type="load-c" size=18 class="demo-spin-icon-load"></Icon>
                            <div>加载组件中...</div>
                        </Spin>
                    </div>
                    <Upload ref="fileUpload" class="shareOfattrFile"
                            :show-upload-list="true"
                            :on-success="handleSuccess"
                            :max-size="102400"
                            :on-exceeded-size="handleMaxSize"
                            :on-remove="handleRomoveFile"
                            action="/api/upload">
                        <Button type="ghost" icon="ios-cloud-upload-outline">上传附件</Button>
                    </Upload>
                </div>
                <div slot="footer">
                    <Button type="primary" @click='addShareBtn'>确认</Button>
                    <Button @click="cancleAddShareBtn">取消</Button>
                </div>
            </Modal>
        </Card>
        <Modal
                v-model="deleteModel"
                title=""
                :loading="loading"
                @on-ok="okBtn">
            <p>确定删除</p>
        </Modal>
    </div>
</template>

<script>

    import tinymce from 'tinymce';
    import systemApi from '../../api/api'
    import fetchList from '../../api/fetchList'
    import dateFormat from '../../tool/date'
    import codeManage from '../../api/statusCodeManage';
    import validator from '../../tool/validator';
    import Cookies from 'js-cookie';


    export default {
        name: 'briefList',
        data() {
            return {
                addShareModal:false,
                typeList:[
                    {id:1,name:'重大问题通报'},
                    {id:2,name:'专项问题通报'},
                    {id:3,name:'重大项目进度通报'},
                    {id:4,name:'政策性通报'}
                ],
                ruleValidate:{
                    type: [
                        {required: true, message: '请选择通报类型',  trigger: 'change'}
                    ],
                    title: [
                        {required: true, message: '请输入标题', trigger: 'blur'}
                    ]
//                    shareName: [
//                        {required: true, message: '请输入通报人', trigger: 'blur'}
//                    ]

                },



                distributionModal: false,//产品分配模态框
                spinShow:true,
                loading: false,
                deleteModel:false,
                currMainId:null,
                searchItem: {
                    title:'',
                    type:0
                },
                addBriefForm:{
                    type:null,
                    title:null,
                    resume:null,
                    shareName:null,
                    context:null,
                    attach:null,
                },
                editPersonModal:false,
                editPersonForm:{
                    id:0,
                    title:null,
                    phone:null,
                    deptId:null
                },
                listStyle: {
                    width: '350px',
                    height: '300px'
                },
                columns: {
                    url: 'allAPI.getCircularList',
                    cols: [
                        {
                            title: '序号',
                            type: 'index',
                            align: 'center',
                            width: 80
                        },
                        {
                            title: '标题',
                            align: 'center',
                            key: 'title',
                            width: 200
                        },
                        {
                            title: '通报类型',
                            align: 'center',
                            key: 'title',
                            width: 200,
                            render:function (h,params) {
                                let _temptypeList = [
                                    {id:1,name:'重大问题通报'},
                                    {id:2,name:'专项问题通报'},
                                    {id:3,name:'重大项目进度通报'},
                                    {id:4,name:'政策性通报'}
                                ];
                                for(let i=0,j=_temptypeList.length;i<j;i++){
                                    if(_temptypeList[i].id == params.row.type){
                                        return _temptypeList[i].name;
                                    }
                                }
                            }
                        },
                        {
                            title: '阅读人数',
                            align: 'center',
                            key: 'readCount',
                            width: 120
                        },
                        {
                            title: '发布时间',
                            align: 'center',
                            key: 'addTime',
                            width: 200,
                            render:function (h,params) {
                                return dateFormat(params.row.addTime,'YYYY-MM-DD 星期E HH:mm')
                            }
                        },
                        {
                            title: ' '
                        },
                        {
                            title: '操作',
                            key: 'action',
                            width: 150,
                            fixed: 'right',
                            align: 'center',
                            render: (h, params) => {
                                return h('div', [
                                    h('a', {
                                        style: {
                                            color: '#2d8cf0',
                                            marginRight: '13px'
                                        },
                                        on: {
                                            click: () => {
                                                this.deleteModel = true;
                                                this.currMainId = params.row.id;
                                            }
                                        }
                                    }, '删除'),
                                    h('a', {
                                        style: {
                                            color: '#2d8cf0',
                                            marginRight: '13px'
                                        },
                                        on: {
                                            click: () => {
//												this.editChannel(params.row);
                                                this.$router.push({name:'briefDetail',
                                                    query:{id:params.row.id,typeId:params.row.type}})
                                            }
                                        }
                                    }, '查看')
                                ])
                            }

                        }
                    ]
                },

                defaultVal: {    //固定参数  初始化默认参数  page和rows 不需要传递
                    title:'',
                    type:1, //  1=方案技术通报 2=培训课件通报
                    pageNo: 1,
                    pageSize: 20
                },
                filt: {},
                totalNumber: '',   // 更新查询结果 总条数
                totalNumber: 0, // 总数据条数
                pageLimitNum: 20, // 每页限制的条数
                currentPage: 1
            };

        },

        methods: {
//            begin===============
            handleSuccess (res, file) {

            },
            handleMaxSize(file){
                this.$Notice.warning({
                    title: '文件太大',
                    desc: '文件超出最大限制  ' + file.name + ' 太大, 不能超过 100M.'
                });
            },
            handleRomoveFile(){
                const fileList = this.$refs.fileUpload.fileList;
                this.$refs.fileUpload.fileList.splice(fileList.indexOf(file), 1);
            },
            //新建消息窗口
            addNotice() {
                this.$refs.addBriefFormRef.resetFields();
                this.addShareModal = true;
            },
            cancleAddShareBtn(){
                this.addShareModal = false;
                this.resetFormModalInfo();

            },
            // 清理数据
            resetFormModalInfo(){
                this.$refs.addBriefFormRef.resetFields();
                this.$refs.fileUpload.clearFiles();
                tinymce.get('tinymceEditerBrief').setContent("");
                this.addBriefForm.context = '';
                this.addBriefForm.type = 0;

            },
            findNameByTypeId(typeId){
                this.typeList.forEach(function (item,index) {
                    if(item.id == typeId){
                        return item.name;
                    }
                })
            },
// ===========================end ===========
            okBtn(){
                let _this = this;
                systemApi.allAPI.deleteCircular({id:_this.currMainId}).then(
                    res => {
                        if (res.code == 0) {
                            this.$Message.success('删除成功');
                            this.filt = {...this.defaultVal};
                        }else{
                            this.$Message.success('删除失败');
                        }
                    },
                    err => {
                        codeManage.showTipOfStatuCode(err, this);
                    });
            },
            // 显示查询结果集总条数
            tableCall(par) {
                // 表格查询后的回调函数
                this.totalNumber = par;
            },
            changeLimitSize(pageSize) {
                // 每页显示条数的改变
                this.pageLimitNum = pageSize;
            },
            changePage(page) {
                // 当前页改变
                this.currentPage = page;
            },
            // 添加通知接口
            addShareBtn(){
                let _this = this;
                this.$refs.addBriefFormRef.validate((valid) => {
                    if (valid) {
                        let detailContent = tinymce.get('tinymceEditerBrief').getContent();
                        if (detailContent === '' || detailContent == null || detailContent === '<!DOCTYPE html>\n' + '<html>\n' +
                            '<head>\n' + '</head>\n' + '<body>\n' + '\n' + '</body>\n' + '</html>') {
                            this.$Message.error('请输入内容');
                            return;
                        }
                        _this.addBriefForm.context = detailContent;
                        let _par = {...this.addBriefForm};
                        console.log(this.$refs.fileUpload.fileList);
                        let _tempArray = [...this.$refs.fileUpload.fileList];
                        let _parFileList = [];
                        for(let i=0,j=_tempArray.length;i < j;i++){
                            if(_tempArray[i].response.code == 0){
                                _parFileList.push({fullPath:_tempArray[i].response.data.fullPath,name:_tempArray[i].response.data.name});
                            }
                        }
                        _par.attach = JSON.stringify(_parFileList);
                        systemApi.allAPI.addCircular(_par).then(
                            res => {
                                if (res.code == 0) {
                                    this.$Message.success('添加成功');
                                    this.filt = {...this.defaultVal};
                                    this.addShareModal = false;
                                    this.$refs.addBriefFormRef.resetFields();
                                    // 附件清空

                                    tinymce.get('tinymceEditerBrief').setContent('');

                                }
                            },
                            err => {
                                codeManage.showTipOfStatuCode(err, this);
                            })
                    }else{

                    }

                })
            },
            // 编辑人员接口
            editPersonBtn(){
                let _this = this;
                this.$refs.editPersonRef.validate((valid) => {
                    if (valid) {
                        let _par = {};
                        _par.id = _this.editPersonForm.id;
                        _par.title = _this.editPersonForm.title;
                        _par.deptId = _this.editPersonForm.deptId;

                        systemApi.allAPI.editPerson(_par).then(
                            res => {
                                if (res.errorCode === 0) {
                                    this.$Message.success(_this.buildmodal.merName+'编辑成功');
                                }
                            },
                            err => {
                                codeManage.showTipOfStatuCode(err, this);
                            })
                    }else{

                    }

                })
            },

            //删除人员
            deletePersonById(id) {
                systemApi.allAPI.deleteCircular({id:id}).then(
                    res => {
                        if (res.code == 0) {
                            this.$Message.success('删除成功');
                            this.filt = {...this.defaultVal};
                        }else{
                            this.$Message.error('删除失败');
                        }
                    },
                    err => {
                        codeManage.showTipOfStatuCode(err, this);
                    })
            },
            //编辑人员初始化
            editChannel(item) {
                this.editPersonModal = true;
                this.$refs.editPersonRef.resetFields();
                this.editPersonForm = item;
                this.editPersonForm.deptId = item.deptId+"";
            },
            //查询
            searchInfo() {
                let _searchName = this.searchItem.title;
                let _type = this.searchItem.type;
                if(this.searchItem.type ==0 || this.searchItem.type == null || this.searchItem.type == undefined){
                    // 提示
                    this.$Message.warning("请选择查询类型")
                    return false;
                }
                this.filt = {title : _searchName,type : _type};
            },
            intPage(){
                let _this = this;

                this.$nextTick( ()=>{
                    tinymce.init({
                        selector: '#tinymceEditerBrief',
                        branding: false,
                        elementpath: false,
                        height: 400,
                        language: 'zh_CN.GB2312',
                        menubar: '',
                        plugins: [
                            'uploadimage print advlist autolink lists link image charmap  hr anchor pagebreak imagetools',
                            'searchreplace visualblocks visualchars code',
                            'insertdatetime media nonbreaking save table contextmenu directionality',
                            'emoticons paste textcolor colorpicker textpattern imagetools codesample'
                        ],
                        toolbar: 'undo redo ' +
                        '| insert | styleselect | forecolor backcolor bold italic ' +
                        '| alignleft aligncenter alignright alignjustify ' +
                        '| bullist numlist outdent indent | ' +
                        'uploadimage',
                        autosave_interval: '20s',
                        image_advtab: true,
                        table_default_styles: {
                            width: '100%',
                            borderCollapse: 'collapse'
                        },
                        setup: function (editor) {
                            editor.on('init', function (e) {
                                _this.spinShow = false;
                            });
                        }
                    });
                });

            }
        },
        created(){
            this.intPage();
        }
    }
</script>


<style lang="less">

    @import "../../styles/main";

    .addShareModal-form{
        .itemsStyle{
            width: 250px;
        }
    }
    .shareOfattrFile .ivu-upload-list-remove{
        font-size: 20px;
        color: red !important;
        font-weight: 800;
    }
    .shareOfattrFile{
        margin-top: 10px;
    }
    .brief-list {

        padding: 16px;
        .itemsStyle{
            width: 250px;
        }

        .search-form {
            padding: 10px 0;
            height: 40px;
            background: white;

        }
        .search-result {
            padding: 0px 0;
        }

    }

    .channel-ivu-transfer {
        display: flex;
        align-items: center;
        justify-content: center;
        margin-top: 35px;
        margin-bottom: 35px;
        .ivu-modal {
            top: 0;
        }
    }


</style>